//
//  CLMvvmViewController.m
//  Charles
//
//  Created by Leo on 2017/6/8.
//  Copyright © 2017年 charles. All rights reserved.
//

#import "CLMvvmViewController.h"
#import "CLMovieModel.h"
#import "CLMovieCell.h"
#import "CLMovieViewModel.h"


@interface CLMvvmViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong) NSArray *modelArray;

@end

@implementation CLMvvmViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpView];
}

- (void)setUpView {
    self.title = @"电影首页";
    self.view.backgroundColor = [UIColor redColor];
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.rowHeight = 80;
    [self.view addSubview:tableView];
    [tableView registerClass:[CLMovieCell class] forCellReuseIdentifier:@"CLMovieCell"];
    
    //初始化CLMovieViewModel，设置成功（returnBlock）和失败的回调（errorBlock），getMovieData去请求数据，请求数据成功即回调上一步设置的returnBlock，请求失败则回调errorBlock
    CLMovieViewModel *viewModel = [[CLMovieViewModel alloc] init];
    viewModel.returnBlock = ^(id returnValue){
        _modelArray = returnValue;
        [tableView reloadData];
    };
    viewModel.errorBlock = ^(id errorCode){
        NSLog(@"%@",errorCode);
    };
    
    [viewModel getMovieData];

}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _modelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CLMovieCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CLMovieCell"];
    cell.model = _modelArray[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CLMovieViewModel *movieViewModel = [[CLMovieViewModel alloc] init];
    [movieViewModel movieDetailWithPublicModel:_modelArray[indexPath.row] WithViewController:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
